package Q3;
/*
拷贝目标文件到指定的地址
 */
import java.io.*;

public class copyFile {
    private File file;
    private String target_file_path;

    public copyFile(File file, String target_file_path) {
        this.file = file;
        this.target_file_path = target_file_path;
    }

    public void copyAll(File file) {
        File[] files = file.listFiles();
        for (File tf : files) {
            if (tf.isFile()) {
                copyContent(tf,target_file_path);
            }
            if (tf.isDirectory()) {
                String name = tf.getName();
                String path = tf.getPath();
                System.out.println("文件名为：" + name);
                System.out.println("文件路径：" + path);
                File target_file = new File(target_file_path + "/" + path);
//                System.out.println("新名叫："+ target_file_path + "/" + path);
                target_file.mkdirs();
                copyAll(tf);
            }
        }
    }

    public void copyContent(File file, String target_file_path) {
        //1.创建BufferedReader对象与被拷贝的指定文件关联
        BufferedReader input = null;
        BufferedWriter output = null;
        try {
            input = new BufferedReader(new FileReader(file.getAbsoluteFile()));
            //2.创建BufferedWriter的对象与拷贝的指定文件关联
            output = new BufferedWriter(new FileWriter(target_file_path+"/"+file.getPath()));
            //3.不断地从输入流中读取字符串并写入到输出流中
            System.out.println("正在拷贝文件： " + file.getName());
            String str = null;
            while ((str = input.readLine()) != null) {
                output.write(str);
            }
            System.out.println("文件 " + file.getPath() + " 拷贝成功!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4 关闭流对象并释放有关的资源
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != input) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
